<?php

namespace app\extra\SmsSDK;

use think\Config as Configbn;
class Upyun {

    public $_key;
    public $_sendUrl;
    public $_code;
    public $_smsConf = array();

    public function __construct($params) {
        $this->_token = Configbn::get('upyunmessagekey.token');
        $this->_sendUrl = Configbn::get('upyunmessagekey.sendUrl');
        $this->_smsConf = array(
            3 => array(
                'tpl_id' => 23651,
                'tpl_value' => "#code#={$params['code']}"),//忘记密码
            1 => array(
                'tpl_id' => 23650,
                'tpl_value' => "#code#={$params['code']}"//注册
            ),
            2 => array(
                'tpl_id' => 23650,
                'tpl_value' => "#code#={$params['code']}"//绑定
            ),);
    }

    /**
     * 校验，写入日志
     * type  1 => "注册", 2 => "绑定",3 => "忘记密码"
     *
     * @param type $type
     */
    public function validate($params) {
        $type   = $params['register'];
        $mobile = $params['mobile'];
        $code   = $params['code'];
        $ip = \app\common\business\log\SmsIp::getClientIp();
        $longIp = ip2long($ip);
        if ($longIp == -1 || $longIp === FALSE) {
            \Error\ErrorModel::throwException(100001, '系统拥堵，请稍候再试');
        }
        $data = array(
            'log_type' => $type,
            'ip' => $longIp,
            'request_ip' => $ip,
            'request_uri' => (empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI']),
            'add_time' => time(),
            'mobile' => $mobile,
        );

//        if ($this->validateIp($type, $longIp)) {
//            $data['status'] = 1;
//            return \app\common\business\log\SmsIp::insertSmsLog($data,$code);
//        } else {
//            $data['status'] = 2;
//            \app\common\business\log\SmsIp::insertSmsLog($data,$code);
//            exception("系统拥堵，请稍候再试", 100001);
//        }
    }
    /**
     * 校验IP
     *
     * @param type $type
     * @param type $ip
     * @param type $maxNum
     * @return boolean
     */
    protected function validateIp($type, $ip, $maxNum = 3) {

        $where = array(
            'log_type' => $type,
            'ip' => $ip,
        );
        $totalNum = \app\common\business\log\SmsIp::getIptotal($where);
        $totalNum = $totalNum ? $totalNum[0]['total'] : 0;
        if ($maxNum > $totalNum) {
            return true;
        } else {
            return false;
        }
    }

    public function pushmessage($params = array()) {

        $this->validate($params);
        $smsConf = array(
            'token' => $this->_token, //您申请的APPKEY
            'mobile' => $params['mobile'], //接受短信的用户手机号码
            'template_id' => 64, //您申请的短信模板ID，根据实际情况修改
            'vars' => 1234 //您设置的模板变量，根据实际情况修改
        );

        $content = $this->juhecurl($smsConf, 1); //请求发送短信
        if ($content) {
            $result = json_decode($content, true);
            $error_code = $result['error_code'];
            if ($error_code == 0) {
                //状态为0，说明短信发送成功
                return "短信发送成功,短信ID：" . $result['result']['sid'];
            } else {
                //状态非0，说明失败
                $msg = $result['reason'];

                exception("短信发送失败(" . $error_code . ")：" . $msg, 102);
            }
        } else {
            exception("请求发送短信失败", 102);
        }
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($params = false, $ispost = 0) {
        echo '<pre>';
        print_r($params);
        echo '</pre>';
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $this->_sendUrl);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $this->_sendUrl . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $this->_sendUrl);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

}
